package eu.tsp.isensors.communication.api;

import com.sun.jersey.spi.container.servlet.ServletContainer;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import org.osgi.util.tracker.ServiceTracker;

import org.apache.felix.ipojo.annotations.Component;

import org.apache.felix.ipojo.annotations.Invalidate;

import org.apache.felix.ipojo.annotations.Requires;

import org.apache.felix.ipojo.annotations.Validate;

import org.apache.felix.ipojo.annotations.Instantiate;

import org.apache.felix.ipojo.annotations.Bind;
import org.apache.felix.ipojo.annotations.Unbind;
import org.apache.felix.ipojo.annotations.Property;

//import tn.hello.ipojo.service.Hello;

@Component(immediate=true)
public class JerseyComponent {

/*	@Requires
    	public static Hello[] m_hello; // Service Dependency

	public static void invokeHelloServices() {
        	for (int i = 0; i < m_hello.length; i++) {
            		// Update with your name.
            		System.out.println(m_hello[i].sayHello("wassim"));
        	}
    	}
*/

	@Property(mandatory=true)
	String nodeID;

	@Bind
	public void bindHttp(HttpService http) {
        System.out.println("<*> bindHttp !");
        registerServlets(http);
        System.out.println("<*> END bindHttp !"+nodeID);
	}

	@Unbind
	public void unbindHttp(HttpService http) {
        System.out.println("<*> unbindHttp !");
        unregisterServlets(http);
	}

	private void registerServlets(HttpService http) {
        try {
            rawRegisterServlets(http);
        } catch (Exception ie) {
            throw new RuntimeException(ie);
        }
    }

    private void rawRegisterServlets(HttpService http) throws ServletException, NamespaceException, InterruptedException {
        http.registerServlet("/isensors/nodes/"+nodeID, new ServletContainer(), getJerseyServletParams(), null);
    }

    private void unregisterServlets(HttpService http) {
        http.unregister("/isensors/nodes/"+nodeID);
    }

    private Dictionary<String, String> getJerseyServletParams() {
        Dictionary<String, String> jerseyServletParams = new Hashtable<String, String>();
        jerseyServletParams.put("javax.ws.rs.Application", JerseyApplication.class.getName());
        return jerseyServletParams;
    }
}
